package com.cloudy.core.thrift.server;

import org.apache.thrift.TMultiplexedProcessor;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadedSelectorServer;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 服务启动方法
 *  Created by cloudy.xie on 16/11/18.
 */
public class ThriftServerBootstrap implements Runnable{
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private TServer server;
    private int port;
    private Map<String,TProcessor> prcessorMap;

    ThriftServerBootstrap(Map<String,TProcessor> prcessorMap,int port) {
        this.port = port;
        this.prcessorMap = prcessorMap;
    }

    @Override
    public void run() {
        try {
            TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(port);
            // 设置协议工厂为 TBinaryProtocol.Factory
            TBinaryProtocol.Factory proFactory = new TBinaryProtocol.Factory(true, true);

            TMultiplexedProcessor multiProtocol = new TMultiplexedProcessor();
            registerProcessor(multiProtocol, prcessorMap);

            TThreadedSelectorServer.Args tArgs = new TThreadedSelectorServer.Args(serverTransport);
            tArgs.protocolFactory(proFactory).processor(multiProtocol);

            server = new TThreadedSelectorServer(tArgs);
            server.serve();
        }catch (Exception e){
            logger.error("ThriftServerBootstrap-error",e);
        }
    }

    private void registerProcessor(TMultiplexedProcessor multiProtocol, Map<String,TProcessor> processorMap){
        if(processorMap == null || processorMap.isEmpty()){
            return;
        }
        processorMap.forEach((serviceName, processor)->{
            multiProtocol.registerProcessor(serviceName, processor);
            System.out.println("registerProcessor-serviceName="+serviceName);
        });
    }

    void close() {
        server.stop();
    }

}
